package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.constant.BusinessStatusConstants;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.dto.business.BusinessPoolListDTO;
import com.qk.dto.business.UpdateBusinessInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.entity.User;
import com.qk.enums.ParamEnum;
import com.qk.exception.CommonException;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.util.CurrentUserContextHolders;
import com.qk.vo.business.BusinessTrackRecordVO;
import com.qk.vo.business.BusinessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@SuppressWarnings("all")
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Override
    public PageResult<BusinessDO> businessList(BusinessListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<BusinessDO> list = this.baseMapper.selectByPage(dto);
        Page<BusinessDO> page = (Page<BusinessDO>) list;
        return PageResult.<BusinessDO>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addBusiness(BusinessDTO dto) {
        //校验参数
        if (ObjectUtil.isEmpty(dto.getName()) || ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getChannel())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //将DTO转换成实体bean拷贝
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.insert(business);
    }

    @Override
    public BusinessVO getBusinessById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        Integer userId = business.getUserId();
        User user = userMapper.selectById(userId);
        List<BusinessTrackRecord> businessTrackRecords = businessTrackRecordMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                .in(BusinessTrackRecord::getBusinessId, id));
        BusinessVO businessVO = BeanUtil.copyProperties(business, BusinessVO.class);
        List<BusinessTrackRecordVO> list = businessTrackRecords.stream().map(item -> {
            BusinessTrackRecordVO recordVO = BeanUtil.copyProperties(item, BusinessTrackRecordVO.class);
            recordVO.setAssignName(user.getName());
            return recordVO;
        }).toList();
        businessVO.setTrackRecords(list);
        return businessVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBusinessInfoById(UpdateBusinessInfoDTO dto) {
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setUpdateTime(LocalDateTime.now());
        if(dto.getStatus() == BusinessStatusConstants.WAIT_FOLLOW_UP){
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(business);
        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecord.setId(null);
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        businessTrackRecord.setBusinessId(business.getId());
        businessTrackRecordMapper.insert(businessTrackRecord);

    }

    @Override
    public void backToPool(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.RECYCLE);
        this.baseMapper.updateById(business);
    }

    @Override
    public void toCustomer(Integer id) {
        //修改商机状态为转客户
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.CONVERT_TO_CUSTOMER);
        try {
            this.baseMapper.updateById(business);
        } catch (Exception e) {
            log.error("修改商机状态为转客户失败", e);
        }
        //新增信息至客户表
        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        //补全信息
        customer.setId(null);
        customer.setBusinessId(id);
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        try {
            customerMapper.insert(customer);
        } catch (Exception e) {
            log.error("新增信息至客户表失败", e);
        }
    }

    @Override
    public PageResult<Business> businessPoolList(BusinessPoolListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Business> page = (Page<Business>) this.baseMapper.selectBusinessPoolList(dto);
        return PageResult.<Business>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
}